package com.qqhf.hitfood.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qqhf.common.entity.AjaxResult;
import com.qqhf.common.entity.PageEntity;
import com.qqhf.hitfood.bean.core.BaseController;
import com.qqhf.hitfood.bean.dto.BizShopDto;
import com.qqhf.hitfood.bean.entity.BizFood;
import com.qqhf.hitfood.bean.entity.BizShop;
import com.qqhf.hitfood.bean.entity.TypeShop;
import com.qqhf.hitfood.service.IBizFoodService;
import com.qqhf.hitfood.service.IBizShopService;
import com.qqhf.hitfood.service.ITypeShopService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "B - 店铺 ")
@RestController
@RequestMapping("/biz/shop")
public class BizShopController extends BaseController {
    @Autowired
    private IBizShopService bizShopService;
    @Autowired
    private ITypeShopService typeShopService;
    @Autowired
    private IBizFoodService bizFoodService;

    @GetMapping("/page")
    public AjaxResult page(PageEntity pageEntity, BizShop bizShop) {
        return AjaxResult.success(bizShopService.page(pageEntity.toPage(), Wrappers.lambdaQuery(bizShop)));
    }

    @GetMapping("/list")
    public AjaxResult list(BizShop bizShop) {
        return AjaxResult.success(toDto(bizShopService.list(Wrappers.lambdaQuery(bizShop))));
    }

    @Operation(summary = "筛选店铺：食品分类、店铺分类、排序条件")
    @GetMapping("/searchList")
    public AjaxResult searchList(
            @RequestParam(value = "typeId", required = false) Integer typeId,
            @RequestParam(value = "orderBy", required = false) Integer orderBy,
            @RequestParam(value = "shopTypeIds", required = false) String shopTypeIds
    ) {
        QueryWrapper<BizShop> wrapper = new QueryWrapper<>();
        if (typeId != null && typeId > 0) {
            List<BizFood> foods = bizFoodService.list(new QueryWrapper<BizFood>().eq("type_id", typeId));
            System.out.println("foods:" + foods);
            if (foods != null && foods.size() > 0) {
                Set<Integer> shopIds = new HashSet<>();
                for (BizFood food : foods) {
                    shopIds.add(food.getShopId());
                }
                System.out.println("shopIds:" + shopIds);
                wrapper.in("id", shopIds);
            }else{
                return AjaxResult.success(new ArrayList<>());
            }
        }
        if (shopTypeIds != null && shopTypeIds.length() > 0) {
            Object[] objects = Arrays.stream(shopTypeIds.split(",")).toArray();
            wrapper.in("type_id", objects);
        }
        if (orderBy != null && orderBy >= 0) {
            String orderCol = (orderBy == 0 ? "sales_ttl" : "sales_mth");
            wrapper.orderByDesc(orderCol);
        }
        return AjaxResult.success(toDto(bizShopService.list(wrapper)));
    }


    @Operation(summary = "搜索店铺：名称、类型")
    @GetMapping("/search")
    public AjaxResult search(
            @Parameter(name = "keyword", description = "关键字")
            @RequestParam(value = "keyword", required = false) String keyword,
            @Parameter(name = "typeId", description = "店铺类型ID")
            @RequestParam(value = "typeId", required = false) Integer typeId) {
        List<BizShop> result = bizShopService.list();
        if (keyword != null) {
            List<BizShop> list = bizShopService.list(new QueryWrapper<BizShop>().like("name", keyword));
            List<BizShop> introList = bizShopService.list(new QueryWrapper<BizShop>().like("intro", keyword));
            result = Stream.of(list, introList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        }
        if (typeId != null) {
            result = result.stream().filter(item -> item.getTypeId().equals(typeId)).collect(Collectors.toList());
        }
        List<BizShopDto> bizShopDtos = toDto(result);
        return AjaxResult.success(bizShopDtos);
    }

    @Operation(summary = "添加店铺")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody BizShop bizShop) {
        BizShop bizShop1 = bizShopService.getOne(new QueryWrapper<BizShop>().eq("name", bizShop.getName()), false);
        if (bizShop1 == null) {
            return AjaxResult.success(bizShopService.save(bizShop));
        }
        return AjaxResult.error("该店铺已存在");
    }

    @Operation(summary = "编辑店铺")
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody BizShop bizShop) {
        return AjaxResult.success(bizShopService.updateById(bizShop));
    }

    @Operation(summary = "删除店铺")
    @DeleteMapping("/delete/{ids}")
    public AjaxResult delete(@PathVariable Integer[] ids) {
        return AjaxResult.success(bizShopService.removeByIds(Arrays.asList(ids)));
    }

    @Operation(summary = "批量删除店铺")
    @GetMapping(value = "/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Integer id) {
        return AjaxResult.success(bizShopService.getById(id));
    }

    /**
     * 包装后类型从id变为文字名称
     *
     * @param list
     * @return
     */
    public List<BizShopDto> toDto(List<BizShop> list) {
        List<TypeShop> typeList = typeShopService.list();
        HashMap<Integer, String> map = new HashMap<>();
        for (int i = 0; i < typeList.size(); i++) {
            TypeShop typeShop = typeList.get(i);
            map.put(typeShop.getId(), typeShop.getName());
        }
        List<BizShopDto> bizShopDtos = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            BizShop bizShop = list.get(i);
            BizShopDto bizShopDto = new BizShopDto();
            BeanUtils.copyProperties(bizShop, bizShopDto);
            bizShopDto.setType(map.get(bizShop.getTypeId()));
            bizShopDtos.add(bizShopDto);
        }
        return bizShopDtos;
    }
}
